﻿@using Newtouch.Infrastructure;
@{
    ViewBag.Title = "WordForm";
    Layout = "~/Views/Shared/_Index.cshtml";
}
<style>
    .ui-jqgrid .ui-jqgrid-btable tbody tr.jqgrow td {
        border: 1px solid #ddd;
    }
    #gridwordPager_center {
        display: none;
    }
    #linkwzlr .ui-th-ltr, #linkwzlr .ui-jqgrid .ui-jqgrid-htable th.ui-th-ltr {
        border: solid 1px #ddd;
    }
</style>
<link href="@SiteUrl.GetStaticResourceScriptUrl("~/Content/css/cispage.css", false)" rel="stylesheet" />
<script src="@SiteUrl.GetStaticResourceScriptUrl("~/js/validate/jquery.validate.min.js")"></script>
<link href="@SiteUrl.GetStaticResourceScriptUrl("~/Content/css/wmgridmenu.css", false)" rel="stylesheet" />
<div id="linkwzlr" style="width:100%;">
    <table id="gridword"></table>
    <table id="gridwordPager"></table>
    <form id="form1">
        <table class="form" style="margin-top:10px;">
            <tr>
                <th class="formTitle"><span class="required">*</span>模板名称: </th>
                <td class="formValue">
                    <input id="mbmc" name="mbmc" type="text" class="form-control required" />
                </td>
                <td class="formTitle">模板类型：</td>
                <td class="formValue">
                    <select id="mblx" class="form-control required">
                        <option value="">==请选择==</option>
                    </select>
                </td>
                <td class="formValue">
                    <input type="button" id="" class="btn btn-primary" value="保存" style="margin-left:20%; width:20%;" onclick="Save()" />
                    <input type="button" id="" class="btn btn-primary" value="删除" style="margin-left:10%; width:20%;" onclick="Delete()" />
                </td>
                <td></td>
            </tr>
        </table>
    </form>
</div>

<script>
    var mbId = $.request("mbId");
    var localdata = [];//带药对象
    var deldata = [];//删除对象
    $(function () {
        gridword();

        $("#mblx").bindSelect({
            url: "/MedicalRecord/GetMbqxSelectJson",
        });

		    if (mbId) {
            $.najax({
                url: "/DoctorManage/DoctorsAdvice/GetMBDetailByMainId",
                dataType: "json",
                data: { Id: mbId },
                type: "POST",
                success: function (localdata) {
                    if (localdata !== typeof (undefined) && localdata.length > 0) {
                        $.each(localdata, function () {
                            this.action = getWordActionStr();
                        });
                        $("#gridword").jqGrid('setGridParam', {
                            datatype: 'local',
                            data: localdata
                        }).trigger("reloadGrid");
                        $('#mblx').val(localdata[0].tcfw).trigger("change");
                        $('#mbmc').val(localdata[0].tcmc);
                    }
                }
            });
        }
    });

    //列表
    function gridword() {
        var $gridword = $("#gridword");
        $gridword.jqGrid({
            datatype: 'local',
            data: localdata,
            height: $(window).height() - 200,
            shrinkToFit: true,   //true:按比例初始化列宽度 false:使用colModel指定的宽度
            autowidth: true,
            rownumbers: true,  //是否显示序号
            editurl: "clientArray",  //行编辑不向服务器提交数据
            unwritten: false,
            colModel: [
                {label: 'Id', name: 'Id', width: 120, editwidth: '81%', align: 'center', hidden: true},
                {label: '<span class="required">*</span>指示', name: 'xmmc', width: 300, editwidth: '100%', align: 'center', editable: true, editrules: { required: true }},
                { label: 'xmdm', name: 'xmdm', width: 100, editwidth: '100%', align: 'center', editable: true, hidden: true },
                { label: '<span class="required">*</span>频次', name: 'pcmc', width: 60, editwidth: '100%', align: 'center', editrules: { required: true }, editable: true },
                { label: 'pcCode', name: 'pcCode', editwidth: '100%', align: 'center', editable: true, hidden: true },
                { label: 'zxcs', name: 'zxcs', editable: true, hidden: true },
                { label: 'zxzq', name: 'zxzq', editable: true, hidden: true },
                { label: 'zxzqdw', name: 'zxzqdw', editable: true, hidden: true },
                { label: '嘱托', name: 'ztnr', width: 310, editwidth: '100%', align: 'center', editable: true },
                { label: '操作', name: 'action', width: 30, align: 'center' },
                { name: 'yzlx', hidden: true }
            ],
            editinputwidthborder: false,    //是否需要边框 默认为true
            editinputborderradius: false,   //是否需要边框圆角 默认true（有圆角）
            pager: "gridwordPager",
            loadComplete: function () {
                if (localdata && localdata.length == 0) {
                    newWordPresData();
                }
            },
            gridComplete: function () {
                EnableWordInlineEditBox();
                //隐藏grid底部滚动条
                $gridword.closest(".ui-jqgrid-bdiv").css({ "overflow-x": "hidden" });
            }
        });

        //二级菜单
        $gridword.jqGrid('setGroupHeaders', {
            useColSpanStyle: true,
            groupHeaders: [
                {
                    startColumnName: 'xmmc',
                    numberOfColumns: 3,
                    titleText: '基本信息'
                }]
        });

        //自定义按钮
        $gridword.navGrid('#gridwordPager',
            { edit: false, add: false, del: false, search: false, refresh: false, view: false, position: "left", cloneToTop: false })
            .navButtonAdd('#gridwordPager',
            {
                buttonicon: "glyphicon glyphicon-new-window",
                title: "新明细",
                caption: "新明细",
                position: "first",
                onClickButton: function () {
                    newWordPresData();
                },
            })
    }

    //启用行内编辑
    function EnableWordInlineEditBox() {
        var ids = $("#gridword").getDataIDs();
        $.each(ids, function () {
            var rowid = String(this);
            //打开编辑模式
            $("#gridword").jqGrid('editRow', rowid, false, initWordInlineFunc);
        });
    }

    //初始化 浮层
    function initWordInlineFunc(rowid) {
        //部分列只读
        $("#" + rowid + "_pcmc").attr('readonly', 'true');
        //频次浮层
        $("#" + rowid + "_pcmc").pcFloatingSelector({
            showtext: 'yzpcmc',
            attrcols: ['yzpcmc', 'yzpcCode', 'zxcs', 'zxzq', 'zxzqdw'],
            itemdbclickhandler: function ($this) {
                $("#" + rowid + "_pcmc").val($this.attr('data-yzpcmc'));
                $("#" + rowid + "_pcCode").val($this.attr('data-yzpcCode'));
                $("#" + rowid + "_zxcs").val($this.attr('data-zxcs'))
                $("#" + rowid + "_zxzq").val($this.attr('data-zxzq'))
                $("#" + rowid + "_zxzqdw").val($this.attr('data-zxzqdw'));
            },
        });

        //嘱托浮层
        $("#" + rowid + "_ztnr").ztFloatingSelector({
            height: 100,
            itemdbclickhandler: function ($this) {
                $("#" + rowid + "_ztnr").val($this.attr('data-ztmc'));
            },
        });
    }

    //新增 按钮
    function newWordPresData() {
        var dataRow = {
            Id: Math.random().toString() + new Date().getMilliseconds(),
            xmdm: "999999999999999999",
            yzlx: @Html.Raw(((int)EnumYzlx.Wz).ToString()),//文字录入
            action: getWordActionStr()
        };
        $("#gridword").jqGrid("addRowData", undefined, dataRow, "first");
    }

    //删除明细
    function deleteIRowData(selRowId, recalc) {
        if (!!selRowId) {
           var Id= $("#gridword").jqGrid('getRowData', selRowId).Id;
            $("#gridword").jqGrid("delRowData", selRowId);
            if (Id.indexOf("0.")=='-1') {//记录下来，从数据库删除
                deldata.push(Id);
            }
        }
    }

    function getWordActionStr() {
        return "<input class='btn btn-default btn-md btn_del' type='button' value='Delete' onclick='deleteIRowData($(this).parent().parent().attr(\"id\"))'/>";
    }

      //保存
    function Save() {
        if (ValidateWord()) {//验证数据
            //获取所有行Id，遍历使编辑框处于保存状态
            var rowIds = $("#gridword").jqGrid('getDataIDs');

            for (var i = 0; i < rowIds.length; i++) {
                var saveResult = $("#gridword").saveRow(rowIds[i], null, null, null, function (callbackRowId) { }, null, null);

                if (!saveResult) {
                    EnableWordInlineEditBox();    //重启启用编辑 否则下次Save时会返回false
                    return;   //保存失败，则return
                }
            }
            var gridwordData = $("#gridword").jqGrid('getRowData_AllLine', null, true);
            if (gridwordData.length < 1) {
                $.modalAlert("当前没有保存的套餐内容", 'warning');
            }
            $.each(gridwordData, function () {    //去掉action
                for (var i = 0; i < $(this).length; i++) {
                    delete $(this)[i].action;
                }
            });
            submitService(gridwordData);

        }
    }

    //提交到后台
    function submitService(gridwordData) {
        //套餐表
        var mbObj = {
            Id: mbId,
            tcfw: $('#mblx').val(),//$.currentWindow().$('#current').attr('data-type'),
            tclx: @Html.Raw(((int)EnumYzlx.Wz).ToString()),
            tcmc: $('#mbmc').val()
        }
        $.najax({
            url: "@Url.Action("Submit")",
            dataType: "json",
            data: { mbObj: mbObj, mbDetailList: gridwordData },
            type: "POST",
            loadingtext: "套餐数据保存中，请稍后...",
            success: function (data) {
                $.modalMsg("保存成功", 'success');
                   if(!mbId && data.data){
                    mbId = data.data;
                    $.currentWindow().expandyzlx = @Html.Raw(((int)EnumYzlx.Wz).ToString());
                    
                }
                $.currentWindow().$("#beveltabs a[id='current']").trigger('click');
                location.href = "/TemplateManage/DoctorServiceTemplate/WordForm?mbId=" + mbId;
            }
        });
    }

    //验证
    function ValidateWord() {
        //是否有数据
        var data = $("#gridword").jqGrid('getRowData_AllLine', null, true);
        if (data.length==0) {
            $.modalAlert("缺少套餐数据", 'warning');
            return false;
        }
        return true;
    }

    function Delete() {
        if (mbId == null || mbId == "") {
            $.modalAlert("缺少套餐", "warning");
            return;
        }
            $.najax({
            url: "@Url.Action("Delete")",
            dataType: "json",
            data: { mbId: mbId},
            type: "POST",
            loadingtext: "套餐数据删除中，请稍后...",
            success: function (data) {
                $.modalMsg("删除成功", 'success');
                $.currentWindow().$("#beveltabs a[id='current']").trigger('click');
                location.href = "/TemplateManage/DoctorServiceTemplate/WordForm?mbId=";
            }
        });
    }
</script>


